package beans.orderdemo;

import java.util.Date;
import java.util.HashMap;
import java.util.Map.Entry;

import org.hibernate.Query;
import org.hibernate.Session;

import beans.AbstractPagedQuery;
import domain.Order;

/**
 * 订单查询条件，完成组装相应的查询语句的功能.
 * @author spring
 */
public class OrderQuery extends AbstractPagedQuery<Order> {

    /**
     * 查询条件��ʼʱ��:开始日期.
     */
    private Date startTime;

    /**
     * 查询条件��ʼʱ��:结束日期.
     */
    private Date stopTime;

    /**
     * 查询条件��ʼʱ��:产品名称.
     */
    private String productName;

    /**
     * @return Returns the productName.
     */
    public String getProductName() {
        return productName;
    }

    /**
     * @param pProductName The productName to set.
     */
    public void setProductName(String pProductName) {
        this.productName = pProductName;
    }

    /**
     * @return Returns the startTime.
     */
    public Date getStartTime() {
        return startTime;
    }

    /**
     * @param pStartTime The startTime to set.
     */
    public void setStartTime(Date pStartTime) {
        this.startTime = pStartTime;
    }

    /**
     * @return Returns the stopTime.
     */
    public Date getStopTime() {
        return stopTime;
    }

    /**
     * @param pStopTime The stopTime to set.
     */
    public void setStopTime(Date pStopTime) {
        this.stopTime = pStopTime;
    }

    /**
     * 构建hibernate Query对象.需要构造查询sql语句,并将查询参数设置到Query对象中.
     * @param session hibernate session
     * @param isQueryTotalCount 是否是构造查询纪录总数目的Query.
     * @return hibernate Query
     */
    public Query buildQuery(Session session, boolean isQueryTotalCount) {
        HashMap<String, Object> queryParams = new HashMap<String, Object>();
        StringBuilder sql = new StringBuilder();
        if (isQueryTotalCount) {// 查询总数
            sql.append("select count(*) from Order o where (1=1)");
        } else {
            sql.append("select o from Order o where (1=1)");
        }

        if (null != startTime) {
            queryParams.put("startTime", startTime);
            sql.append(" and (o.orderDate>=:startTime)");

        }
        if (null != stopTime) {
            queryParams.put("stopTime", stopTime);
            sql.append(" and (o.orderDate<=:stopTime)");
        }
        if (null != productName) {
            queryParams.put("productName", productName);
            sql.append(" and (o.productName like :productName)");
        }
        // System.out.println("sql is "+sql.toString());
        Query query = session.createQuery(sql.toString());
        // 设置查询参数
        for (Entry<String, Object> entry : queryParams.entrySet()) {
            query.setParameter(entry.getKey(), queryParams.get(entry.getKey()));
        }
        return query;
    }

}
